package cn.yunyichina.provider.pay.service;

import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.alipay.AddCouponRequest;
import cn.yunyichina.provider.iface.entity.alipay.AlipayRequest;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.pay.entity.PaymentSetting;
import cn.yunyichina.provider.pay.exception.PaySettingNotFoundException;
import cn.yunyichina.utils.commons.DateUtils;
import com.alibaba.fastjson.JSON;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lullaby on 2017/4/12.
 */
public class BaseCouponService extends BaseService {

    protected AlipayRequest buildAddAlipayCouponInstanceParameters(AddCouponRequest request) throws PaySettingNotFoundException {
        String appId = request.getAppId();
        PaymentSetting paymentSetting = getPaymentSetting(appId);
        String signType = "RSA";
        if (paymentSetting.getPayPublicKey().length() > 256) {
            signType = "RSA2";
        }

        String orderNo = request.getOrderNo();
        OrderExtVo orderExtVo = getBaseOrderByOrderNo(orderNo);

        PaymentSetting orderPaymentSetting = getPaymentSetting(orderExtVo.getPayAppId());

        AlipayRequest alipayRequest = new AlipayRequest();
        alipayRequest.setPayPublicKey(paymentSetting.getPayPublicKey());
        alipayRequest.setPublicKey(paymentSetting.getPublicKey());
        alipayRequest.setPrivateKey(paymentSetting.getPrivateKey());
        alipayRequest.setAppId(appId);
        alipayRequest.setMethod("alipay.pass.instance.add");
        alipayRequest.setFormat("json");
        alipayRequest.setCharset("utf-8");
        alipayRequest.setSignType(signType);
        alipayRequest.setTimestamp(DateUtils.dateToString(Calendar.getInstance().getTime()));
        alipayRequest.setVersion("1.0");

        Map<String, Object> bizContent = new HashMap<>();
        // tpl_id
        bizContent.put("tpl_id", request.getTemplateId());

        // tpl_params
        Map<String, Object> tplParams = new HashMap<>();

        tplParams.put("channelID", paymentSetting.getPartnerId());
        tplParams.put("serialNumber", UUIDUtil.get32UUID());

        tplParams.put("couponCode", request.getCouponCode());

        bizContent.put("tpl_params", JSON.toJSON(tplParams));

        // recognition_type
        bizContent.put("recognition_type", "1");

        // recognition_info
        Map<String, String> recognitionInfo = new HashMap<>();
        recognitionInfo.put("partner_id", orderPaymentSetting.getPartnerId());
        recognitionInfo.put("out_trade_no", orderNo);
        bizContent.put("recognition_info", JSON.toJSON(recognitionInfo));

        alipayRequest.setBizContent(JSON.toJSONString(bizContent));

        return alipayRequest;
    }

}
